package cn.zhiquxing.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {


    // 创建Redis连接工厂
//    @Bean(name = "RedisConnectionFactory")
//    public RedisConnectionFactory initRedisConnectionFactory() {
//        // Redis配置
//        RedisStandaloneConfiguration redisCfg = new RedisStandaloneConfiguration("192.168.80.137", 6379);
//        // 设置密码
//        redisCfg.setPassword("abcdefg");
//        // 配置连接池
//        new GenericObjectPoolConfig<Object>();
//        
//        new
//        // 最大空闲数
//        poolConfig.setMaxIdle(30);
//        // 最大连接数
//        poolConfig.setMaxTotal(50);
//        // Lettuce连接池客户端配置，这里使用建造者模式
//        var lettuceCfg = LettucePoolingClientConfiguration.builder()
//                .commandTimeout(Duration.ofSeconds(2)) // 命令超时时间为2s
//                .poolConfig(poolConfig) // 配置连接池
//                .build(); // 创建配置
//        // 创建连接工厂
//        var connectionFactory = new LettuceConnectionFactory(redisCfg, lettuceCfg);
//        return connectionFactory;
//    }
    
    
    @Bean
    @SuppressWarnings(value = { "unchecked", "rawtypes" })
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory)
    {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        FastJsonRedisSerializer serializer = new FastJsonRedisSerializer(Object.class);

        // 使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(serializer);

        // Hash的key也采用StringRedisSerializer的序列化方式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(serializer);

        template.afterPropertiesSet();
        return template;
    }
}
